package com.ibm.datamodel.timeseries.parser;

import com.ibm.cps.message.MessageFactory;
import com.ibm.cps.message.ParsedDataMessage;
import com.ibm.cps.message.RawDataMessage;
import com.ibm.interfaces.ITimeSeriesSchema;
import com.ibm.util.ErrorCode;
import com.ibm.util.exception.CPSException;

import io.protostuff.XmlIOUtil;

/**
 * @author Yaoliang Chen
 * @version Nov 20, 2015 TODO P2 Performance Optimization for tskey extraction
 */
public class XmlParser extends ProtostuffMessageParser {

	public XmlParser(ITimeSeriesSchema schema) throws CPSException {
		super(schema);
	}

	/**
	 * TODO performance optimization
	 */
	@Override
	public Comparable getTimeSeriesKey(byte[] data) throws CPSException {
		RawDataMessage rawMsg = MessageFactory.produceDataMessage(data);
		ParsedDataMessage message = parseDataMessage(rawMsg);
		return message.getTsKey();
	}

	@Override
	public ParsedDataMessage parseDataMessage(RawDataMessage xmlMsg) throws CPSException {
		ParsedDataMessage message = schema.newMessage();
		try {
			XmlIOUtil.mergeFrom(xmlMsg.getMessageBytes(), message, this);
		} catch (Exception e) {
			throw new CPSException(ErrorCode.PARSE_ERROR_CODE, "error while parse the message; " + e.getMessage());
		}
		return message;
	}

	@Override
	public byte[] restoreFromDataMessage(ParsedDataMessage message) throws CPSException {
		return XmlIOUtil.toByteArray(message, this);
	}

}
